import React, { useState } from "react";
import { XfTTS } from "@muguilin/xf-voice-dictation"; // 科大讯飞 TTS 模块

const MaleVoiceComponent: React.FC = () => {
  const [text, setText] = useState<string>("你好，我是数字人助手");
  const [isSpeaking, setIsSpeaking] = useState<boolean>(false);

  // 语音合成函数
  const speak = async () => {
    if (isSpeaking) return;

    setIsSpeaking(true);

    try {
      const tts = new XfTTS({
        APPID: "cda5e010", // 替换为你的科大讯飞 APPID
        APIKey: "ZWZhOGI5ZWQ2OWJhNDVlZjUyOGFkNjE1", // 替换为你的科大讯飞 APIKey
        APISecret: "24838eb4fee9d5a7e7eaf64f861a8fea", // 替换为你的科大讯飞 APISecret
      });

      // 设置男性语音
      tts.setVoiceName("x4_lingfeiyi_oral"); // 替换为科大讯飞提供的男性语音名称

      // 调用 TTS 合成
      const result = await tts.synthesize(text);

      if (result.success) {
        console.log("语音合成成功:", result.audio_url);
        // 播放合成的音频
        const audio = new Audio(result.audio_url);
        audio.play();
      } else {
        console.error("语音合成失败:", result.error);
      }
    } catch (error) {
      console.error("语音合成错误:", error);
    } finally {
      setIsSpeaking(false);
    }
  };

  return (
    <div>
      <h1>数字人语音合成</h1>
      <textarea
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="输入需要合成的文字"
      />
      <button onClick={speak} disabled={isSpeaking}>
        {isSpeaking ? "语音合成中..." : "合成语音"}
      </button>
    </div>
  );
};

export default MaleVoiceComponent;